package bfs;

import java.util.*;

/**
 * BinaryTreeLevelOrderTraversal 二叉树的层序遍历
 *
 * @author <a href="zhaoyingling12@163.com">Zhao Simon</a>
 * @description: https://leetcode-cn.com/problems/binary-tree-level-order-traversal
 * @date 2021/5/12
 **/
public class BinaryTreeLevelOrderTraversal {

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> ans = new ArrayList<>();
            if (root == null) return ans;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                List<Integer> list = new ArrayList<>();
                while (size != 0) {
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    if (node.left != null) queue.offer(node.left);
                    if (node.right != null) queue.offer(node.right);
                    size--;
                }
                ans.add(list);
            }
            return ans;
        }
    }
}
